<!-- 违章 确认费用 -->
<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-ok="submitFn"
    @before-open="onBeforeOpen"
    title="确认费用"
    class="modal-dialog-wrapper"
    unmount-on-close
    :mask-closable="false"
    width="65vw"
  >
    <div class="fee-page">
      <div class="fee-list">
        <div v-for="(item, index) in feeList" :key="index" style="margin: 0 20px">
          <feeitem :fee="item" />
        </div>
        <div class="all-cost">
          <span>合计</span>
          <div class="cost-num">
            <div>{{ costType == 0 ? '应收' : '应付' }}：{{ unitVal(Math.abs(feeCostAmount.receiveAmount), '元') }}</div>
            <div style="margin-top: 16px">
              {{ costType == 0 ? '待收' : '待付' }}：{{ unitVal(Math.abs(feeCostAmount.receivedNotAmount), '元') }}
            </div>
          </div>
        </div>
      </div>

      <a-divider class="custom-divider" />

      <page-form :model="form" layout="vertical" ref="formRef" style="margin-top: 40px">
        <page-form-row>
          <page-form-item
            field="actualAmount"
            :label="costName + '金额'"
            :rules="{ required: true, message: '请输入' + costName + '金额' }"
          >
            <i-input-number v-model="form.actualAmount" unit="元" :precision="2" disabled />
          </page-form-item>
          <page-form-item
            field="paymentWay"
            :label="costName + '方式'"
            :rules="{ required: true, message: '请选择' + costName + '方式' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              placeholder="请选择"
              v-model="form.paymentWay"
              @change="typeChange"
              :disabled="paymentWayDisabled"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>
          <page-form-item
            v-if="form.paymentWay == 4"
            label="选择使用哪笔订单押金"
            field="deductionOrderId"
            :rules="{ required: true, message: '请选择使用哪笔订单押金' }"
            labelTooltipContent="支持选择同一承租人下的芝麻免押押金、违章关联订单如果是线下支付的押金，使用其违章押金抵扣；芝麻免押使用的是租车押金&违章押金；芝麻免押的押金支持查看详情。"
          >
            <template #label-extra>
              <a-link v-if="isShowDeposit" @click="onShowDeposit"> 查看押金详情 </a-link>
            </template>
            <a-select
              placeholder="请选择"
              v-model="form.deductionOrderId"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              popup-container="#app"
            >
              <a-option v-for="(item, index) in memberList" :key="index" :value="item.orderId"> {{ item.orderCode }}</a-option>
            </a-select>
          </page-form-item>
          <page-form-item v-if="form.paymentWay == -1" field="account" label="结算主体" :rules="{ required: true, message: '请选择' }">
            <a-select
              :placeholder="'请选择'"
              v-model="form.account"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="item in accountList" :key="item.id" :value="item.id" :label="item.bank" />
            </a-select>
          </page-form-item>
          <page-form-item
            v-else
            field="account"
            :label="costName + '账号'"
            labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              :placeholder="!form.paymentWay ? '请先选择' + costName + '方式' : '请选择'"
              v-model="form.account"
              :disabled="!form.paymentWay ? true : false"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option
                v-for="item in accountList"
                :key="item.id"
                :value="item.id"
                :label="item.account + (item.bank ? '_' + item.bank : '')"
              />
            </a-select>
          </page-form-item>
          <page-form-item
            v-if="form.paymentWay && form.paymentWay != -1"
            field="paymentTime"
            :label="costName + '时间'"
            :rules="[{ required: true, message: '请选择' + costName + '时间', trigger: 'change' }]"
          >
            <i-date-picker
              class="w-full"
              v-model="form.paymentTime"
              show-time
              value-format="YYYY-MM-DD HH:mm:ss"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              popup-container="#app"
            />
          </page-form-item>
          <page-form-item field="customerName" label="客户名称" :rules="{ required: true, message: '请输入客户名称' }">
            <i-input placeholder="请输入" v-model="form.customerName" :max-length="20" />
          </page-form-item>
          <page-form-item field="customerAccount" :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
            <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
          </page-form-item>
          <page-form-item field="settlementRemark" label="结算备注" size="2/3">
            <i-input placeholder="请输入" v-model="form.settlementRemark" :max-length="200" />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="submitFn" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <qcode-modal v-model:visible="payQCodeModal" @close="payQCodeClose" :details="qrCodeDetails" :from="qrCodeFrom" />
  <!-- 查看押金详情 -->
  <ZhimaDepositFreeModal ref="zhimaDepositFreeModalRef" :orderId="form.deductionOrderId" :showOperateBtn="false" />
</template>

<script setup name="CarMaintenanceConfirmFees" lang="ts">
  import feeitem from './comfirm-fee-item.vue'
  import qcodeModal from '../modals/qcode-modal.vue'
  import ZhimaDepositFreeModal from '../../order/short-order/components/alipay-deposit/zhima-deposit-free-modal.vue'

  import { Message } from '@arco-design/web-vue'
  import { unitVal } from '@/utils'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/order/sOrder'
  import { feetoConfirm, violationToConfirm } from '@/api/finance/costConfirm'
  import { ref, nextTick, computed } from 'vue'
  import { getDepositType, getUsableAmountOrderList } from '@/api/order/sOrder'
  import { getDepositWay } from '@/api/order/czsOrder'
  import useUserStore from '@/store/modules/user'

  const userStore = useUserStore()
  const paywayEnum = ref<any>([]) //收付款方式
  const accountList = ref<any>([]) //收付款账号列表
  const costType = ref() // type  0-收款，1-付款
  const costName = ref('')
  const feeList = ref<any>([]) // 收付款列表
  const feeCostAmount = ref<any>({}) //收付款类型及金额
  const formRef = ref()
  const paymentWayDisabled = ref(false)
  const payQCodeModal = ref(false)
  const form = ref<any>({
    idList: [], //结算单ids
  })

  /**
   * 获取短租订单押金收取方式
   */
  const getSorderInExpWayList = (id: any) => {
    return new Promise((resolve) => {
      getDepositType({ id }).then((res: any) => {
        console.log('res', res)
        const { orderSource, violationDepositFee } = res.result
        resolve({ orderSource, violationDepositFee })
      })
    })
  }

  /**
   * 获取长租订单押金收取方式
   */
  const getLorderInExpWayList = (id: any) => {
    return new Promise((resolve) => {
      getDepositWay({ id }).then((res: any) => {
        console.log('res', res)
        const { orderSource, violationDepositFee } = res.result
        resolve({ orderSource, violationDepositFee })
      })
    })
  }

  const onBeforeOpen = () => {
    userStore.setEpDetail()
  }

  // 打开弹窗
  const okLoading = ref(false)
  const showModal = ref(false)
  const orderDetail = ref<any>({})
  const show = (idList: any, record: any) => {
    console.log('确认费用: ', idList, record)

    // 重置
    resetForm()
    showModal.value = true
    orderDetail.value = record
    form.value.idList = JSON.parse(idList)
    if (form.value.idList) {
      feeConfirm(form.value.idList)
    }
  }

  const payQCodeClose = () => {
    emit('feepageConfirm')
  }

  const onClose = () => {
    showModal.value = false
    okLoading.value = false
  }

  const resetForm = () => {
    paymentWayDisabled.value = false
    paywayEnum.value = []
    accountList.value = []
    form.value = {}
    okLoading.value = false
  }
  // 弹窗获取费用信息详情
  const feeConfirm = (idList: any) => {
    feetoConfirm({ idList: idList }).then(async (res: any) => {
      const result = res.result

      const carAssetFeeItem = result.carAssetFeeList[0]
      const violation = carAssetFeeItem.violation
      feeCostAmount.value = result
      feeList.value = result.carAssetFeeList
      costType.value = result.costType
      form.value.paymentTime = carAssetFeeItem.createTime

      // 5.9.1.1 长短租关联订单确认费用并且是会员显示承租人名称
      if (orderDetail.value.orderId && violation.memberId) {
        form.value.customerName = violation.memberName
      }

      if (costType.value == 0) {
        costName.value = '收款'
        form.value.actualAmount = Math.abs(res.result.receiveAmount) //固定金额，不可修改
      } else {
        costName.value = '付款'
        form.value.actualAmount = Math.abs(res.result.receivedNotAmount) //固定金额，不可修改
      }
      //获取可用押金订单列表
      await getmemberOrderList(violation.memberId, orderDetail.value)
      getType(result.costType, result.carAssetFeeList)
    })
  }

  // 查看押金详情
  const zhimaDepositFreeModalRef = ref()
  const onShowDeposit = () => {
    zhimaDepositFreeModalRef.value.show()
  }

  // 根据承租人ID获取可用押金订单列表
  const memberList = ref([])
  const getmemberOrderList = (memberId: any, orderDetail: any) => {
    return new Promise((resolve) => {
      getUsableAmountOrderList({
        memberId: memberId,
        orderId: orderDetail.orderId,
        orderType: orderDetail.eventType == 4 ? 1 : (orderDetail.eventType == 7 ? 0 : null ), // 1短租 0长租  eventType:4短租 7长租
        payTypeList: [2, 4], //2 线下支付 4 芝麻免押
      }).then((res: any) => {
        if (res.code == 200) {
          memberList.value = res.result
          memberList.value.forEach((item: any) => {
            if (item.orderCode.includes('本单')) {
              form.value.deductionOrderId = item.orderId
            }
          })
        }
        resolve()
      })
    })
  }
  const isShowDeposit = computed(() => {
    if (form.value.deductionOrderId) {
      const item = memberList.value.find((item: any) => item.orderId == form.value.deductionOrderId)
      return item && item.payType == 4
    }
    return false
  })

  // 收付款方式
  const getType = (costType: any, carAssetFeeList = []) => {
    console.log('getType: ', costType, carAssetFeeList)

    const is_offline = carAssetFeeList.every((item: any) => item.feeType == 1)
    console.log('is_offline', is_offline)

    const is_collection = carAssetFeeList.every((item: any) => item.costType == 0)
    console.log('is_collection', is_collection)

    let is_show_jialian = false
    if (carAssetFeeList.length == 1 && is_collection && form.value.actualAmount > 0) {
      is_show_jialian = true
    } else if (carAssetFeeList.length > 1) {
      if (is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      } else if (!is_collection && form.value.actualAmount > 0) {
        is_show_jialian = true
      }
    }
    console.log('is_show_jialian', is_show_jialian)

    const syncInventory: any = userStore.syncInventory

    getAccountByPageData({ type: costType == 0 ? 0 : 1 }).then((res: any) => {
      var data = res.result

      console.log('getAccountByPageData: ', syncInventory.jialianEnabled, form.value.actualAmount)

      // 过滤
      data.forEach((i: any, index: any) => {
        if (orderDetail.value.feeNameId == 551) {
          if (i.way != '2' && i.way != '3' && i.way != '5') {
            paywayEnum.value.push(i)
          }
        } else {
          paywayEnum.value.push(i)
        }

        /**
         * 不显示嘉联聚合支付
         * syncInventory.jialianEnabled: 0 未开通嘉联聚合支付
         * actualAmount: 收款金额小于等于0
         * is_offline: 不是线下费用时
         * is_show_jialian: 是否显示嘉联聚合支付，默认不显示
         */
        if (syncInventory.jialianEnabled == 0 || !is_show_jialian || !is_offline) {
          paywayEnum.value = paywayEnum.value.filter((el: any) => el.way != '-1')
        }

        if (data.length == index + 1) {
          // 无押金抵扣项、或只有一笔订单且不是芝麻免押时，过滤掉押金抵扣
          if (memberList.value.length == 1) {
            if (memberList.value[0].payType == 2) {
              getPayType()
            } else if (memberList.value[0].payType != 4) {
              filterPayType()
            }
          } else if (!memberList.value.length) {
            filterPayType()
          }
        }
      })
    })
  }

  // 过滤押金抵扣
  const filterPayType = () => {
    paywayEnum.value.forEach((i: any, index: any) => {
      if (i.way == 4) {
        nextTick(() => {
          paywayEnum.value.splice(index, 1)
        })
      }
    })
  }

  const getPayType = () => {
    // 收款
    if (costType.value == 0) {
      // 关联订单
      if (orderDetail.value.orderId) {
        // eventType: 7 长租  4 短租
        if (orderDetail.value.eventType == 7) {
          // 获取长租订单详情
          getLorderInExpWayList(orderDetail.value.orderId).then((res: any) => {
            // 线下订单
            if (res.orderSource == 1) {
              // 未缴纳违章押金
              if (!res.violationDepositFee || res.violationDepositFee.feeStatus == 1) {
                paymentWayDisabled.value = false
                filterPayType()
                console.log('未显示押金抵扣原因：未缴纳违章押金')
              } else {
                // 已缴纳违章押金
              }
            } else {
              // OTA渠道订单
            }
          })
        } else {
          // 获取短租订单详情
          getSorderInExpWayList(orderDetail.value.orderId).then((res: any) => {
            // 线下订单
            if (res.orderSource == 1) {
              // 未缴纳违章押金
              if (!res.violationDepositFee || res.violationDepositFee.feeStatus == 1) {
                paymentWayDisabled.value = false
                filterPayType()
                console.log('未显示押金抵扣原因：未缴纳违章押金')
              } else {
                // 已缴纳违章押金
              }
            } else {
              // OTA渠道订单
            }
          })
        }
      } else {
        // 未关联订单
        paymentWayDisabled.value = false
        filterPayType()
        console.log('未显示押金抵扣原因：未关联订单')
      }
    } else {
      // 付款
      paymentWayDisabled.value = false
      filterPayType()
      console.log('未显示押金抵扣原因：付款')
    }
  }
  // 账号
  const typeChange = (e: any) => {
    if (e) {
      form.value.account = ''
    }
    paywayEnum.value.forEach((el: any) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: costType.value == 0 ? 0 : 1 }).then((res: any) => {
          if (res.result.length == 1 && form.value.paymentWay == -1) {
            form.value.account = res.result[0].id
          }

          accountList.value = res.result
          console.log('accountList', accountList.value)
        })
      }
    })
  }
  const emit = defineEmits(['feepageConfirm'])

  const qrCodeDetails = ref()
  const qrCodeFrom = ref('')

  const submitFn = () => {
    okLoading.value = true
    formRef.value.validate((error: any) => {
      if (!error) {
        const param = {
          ...form.value,
          orderId: orderDetail.value.orderId,
        }
        // 选择使用哪笔订单押金后，需要传入订单类型
        if (form.value.paymentWay == 4) {
          param.deductionOrderType = memberList.value.find((item: any) => item.orderId == form.value.deductionOrderId)?.orderType
        }
        violationToConfirm(param)
          .then((res: any) => {
            if (form.value.paymentWay == -1) {
              qrCodeFrom.value = 'violationConfirmFee'
              qrCodeDetails.value = { qrcodeId: res.result }
              showModal.value = false
              payQCodeModal.value = true
            } else {
              Message.success(res.message)
              showModal.value = false
              emit('feepageConfirm')
            }
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        okLoading.value = false
      }
    })
  }
  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  .fee-list {
    padding-top: 20px;
    border: 1px solid #f2f3f5;
  }
  .all-cost {
    font-weight: 600;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    height: 100px;
    .cost-num {
      color: #1890ff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }
  // 弹窗添加的样式
  .fee-page {
    width: 100%;
    max-height: 70vh;
    position: relative;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
</style>
